#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年4月1日

@author: chenyongbing
'''
import sys,os,datetime
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
import logging
sys.path.append(os.path.join(current_dir,'../../'))
from base.PyMySQL import ConnectMySQL
from base.localConfig import baseLocalConfig

zhimind_host = baseLocalConfig.mysqlConfig['zhimind']['host']
zhimind_port = baseLocalConfig.mysqlConfig['zhimind']['port']
zhimind_user = baseLocalConfig.mysqlConfig['zhimind']['user']
zhimind_passwd = baseLocalConfig.mysqlConfig['zhimind']['passwd']
zhimind_db = baseLocalConfig.mysqlConfig['zhimind']['db']
myZhimind = ConnectMySQL(host=zhimind_host, user=zhimind_user, password=zhimind_passwd, db=zhimind_db)



def select_many(sql,qlist):
    db = myZhimind.pool.connection()
    cur = db.cursor()
    count = cur.executemany(sql,qlist)

    if count==0:return []
    result = cur.fetchall()
    db.commit()
    cur.close()
    db.close()
    if result==None:result=[]
    return result


#repair role

#repair delta_day

def repair_dalta_day(pfile='repair_sql.txt'):
    query = 'select day,dgroup,mac from mac_customer_stats where role=3 and first_day!=day'
    rets = myZhimind.SelectAll(query)
    if rets==None:rets = []
    fr = open(pfile,'a+')
    for day,dgroup,mac in rets:
        query = 'select dgroup,mac,max(day) from mac_customer_stats where dgroup="%s" and mac="%s" and day<"%s"'%(dgroup,mac,day)
        ret = myZhimind.SelectOne(query)
        if ret==None:
            print "can not find."
            continue
        s_dgroup,s_mac,max_day = ret
        if s_dgroup==None or s_mac==None or max_day==None:
            print "update first_day"
            sql = 'update mac_customer_stats set first_day="%s" where dgroup="%s" and mac="%s" and day="%s"'%(day,dgroup,mac,day)
            #continue
        else:
            delta_day = (day -max_day).days
            sql = 'update mac_customer_stats set delta_day="%s" where dgroup="%s" and mac="%s" and day="%s"'%(delta_day,dgroup,mac,day)
            #delta_day = (datetime.date(int(day[:4]),int(day[5:7]),int(day[8:10])) -datetime.date(int(max_day[:4]),int(max_day[5:7]),int(max_day[8:10]))).days
            #print dgroup,mac,day,max_day,delta_day
        fr.write('%s;\n'%(sql))




def repair_dalta_day_by_day():
    query = 'select dgroup,mac,day from mac_customer_stats where role=3 and first_day!=day'
    rets = myZhimind.SelectAll(query)
    if rets==None:rets = []
    datas = {}
    for dgroup,mac,day in rets:
        pass
    
    sql = 'select dgroup,mac,max(day) from mac_customer_stats where dgroup=%s and mac=%s and day<%s'
    
    
    srets = select_many(sql,rets)
    for dgroup,mac,max_day in srets:
        print dgroup,mac,max_day
        
        
repair_dalta_day()     

    